//
//  QIETimerTool.m
//  QGTestTimer
//
//  Created by 李超群 on 2019/3/21.
//  Copyright © 2019 李超群. All rights reserved.
//

#import "SCTimerTool.h"

@interface SCTimerModel : NSObject

/** 是否重复 */
@property (nonatomic, assign) BOOL repeat;

/** 计时器的时间间隔 */
@property (nonatomic, assign)NSTimeInterval timeInterval;

/** 回调的 block */
@property (nonatomic, copy) QIETimerToolCallBackBlock callback;

/** 计时器 ModelId */
@property (nonatomic, copy) NSString *timerIdentifier;

/** 这个model 加入到计时器的时间 */
@property (nonatomic, assign)NSTimeInterval  startTimeValue;

@end

@implementation SCTimerModel

/** 初始化方法 */
+(instancetype)creatLiveRoomTimerModelWithTimeInterval:(NSTimeInterval)timeInterval repeat:(BOOL)repeat callback:(QIETimerToolCallBackBlock)callback{
    SCTimerModel *model = [[SCTimerModel alloc]init];
    model.timeInterval = timeInterval;
    model.repeat = repeat;
    model.callback = callback;
    return model;
}

@end

@interface SCTimerTool ()

/** 计时器 */
@property(nonatomic,strong) dispatch_source_t timer;

/** 计时器的线程 */
@property (nonatomic, strong) dispatch_queue_t queue;

/** 累计的时间 */
@property (nonatomic, assign) NSTimeInterval totalTimerValue;

/** 计时器 ModelId */
@property (nonatomic, copy) NSString *timerIdentifier;

/** 计时器和事件的关系映射表 */
@property (nonatomic, strong) NSMutableDictionary <NSString *, NSMutableSet *> *timerActionDic;

/** 计时器 model 和 id 的关系映射表 */
@property (nonatomic, strong) NSMutableDictionary *modelsDic;

/** 自增的计时器 id */
@property (nonatomic, assign) int timerId;

@end

@implementation SCTimerTool

- (instancetype)init{
    if (self = [super init]) {
        
        // - 创建计时器和事件的关系映射表
        self.timerActionDic = [[NSMutableDictionary  alloc] init];
        self.modelsDic = [[NSMutableDictionary  alloc] init];
        
        /** 开始计时器 */
        [self starTimer];
    }
    return self;
}

/** 开始计时器 */
-(void)starTimer{
    // - 创建一个每0.1s 执行一次的计时器
    NSTimeInterval timeInterval = 1;
    _queue = dispatch_queue_create("com.tencent.tv.timerTool.queue", DISPATCH_QUEUE_SERIAL);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _queue);
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeInterval * NSEC_PER_SEC));
    uint64_t interval = (uint64_t)(timeInterval * NSEC_PER_SEC);
    dispatch_source_set_timer(_timer, start, interval, 0);
    dispatch_source_set_event_handler(_timer, ^{
        self.totalTimerValue = self.totalTimerValue + timeInterval;
    });
    dispatch_resume(_timer);
}

/** 重写累计时间的 set 方法 */
-(void)setTotalTimerValue:(NSTimeInterval)totalTimerValue{
    _totalTimerValue = totalTimerValue;
    NSString *timerAcitonKey = [NSString stringWithFormat:@"%.1f", (self.totalTimerValue)];
    NSMutableSet *timerModesSet = [self.timerActionDic objectForKey:timerAcitonKey];
    [timerModesSet enumerateObjectsUsingBlock:^(SCTimerModel *pModel, BOOL * _Nonnull stop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            !pModel.callback ? : pModel.callback() ;
        });
        [self removeTimerActionWithId:pModel.timerIdentifier];
        if (pModel.repeat){
            [self addLiveRoomTimerModel:pModel];
        }
    }];
}
/** 根据 timerid 生产 timerIdentifier */
-(NSString *)timerIdentifier{
    return [NSString stringWithFormat:@"tiemrId_%d", self.timerId];
}

/** 直接创建一个计时器 */
-(NSString *)addTimerActionWithTimeInterval:(NSTimeInterval)timeInterval repeat:(BOOL)repeat callback:(QIETimerToolCallBackBlock)callback{
    SCTimerModel *model = [SCTimerModel creatLiveRoomTimerModelWithTimeInterval:timeInterval repeat:repeat callback:callback];
    self.timerId++;
    model.timerIdentifier = [self timerIdentifier];
    [self addLiveRoomTimerModel:model];
    return model.timerIdentifier;
}

/** 添加一个计时器事件 */
-(void)addLiveRoomTimerModel:(SCTimerModel *)liveRoomTimerModel{
    dispatch_block_t block = ^{
        liveRoomTimerModel.startTimeValue = self.totalTimerValue + liveRoomTimerModel.timeInterval;
        NSString *key = [NSString stringWithFormat:@"%.1f", liveRoomTimerModel.startTimeValue];
        NSMutableSet *timerModesSet = [self.timerActionDic objectForKey:key];
        timerModesSet = timerModesSet ? : [NSMutableSet set];
        [self.timerActionDic setObject:timerModesSet forKey:key];
        [self.modelsDic setObject:liveRoomTimerModel forKey:liveRoomTimerModel.timerIdentifier];
        [timerModesSet addObject:liveRoomTimerModel];
    };
    dispatch_async(self.queue, block);
}

/** 计时器是否在工作 */
-(BOOL)timerWorking:(NSString *)timerIdentifier{
    return !![self.modelsDic objectForKey:timerIdentifier];
}

/** 删除一个计时器的事件 */
-(void)removeTimerActionWithId:(NSString *)timerIdentifier{
    if (!timerIdentifier) return;
    dispatch_block_t block = ^{
        SCTimerModel *liveRoomTimerModel = [self.modelsDic objectForKey:timerIdentifier];
        if (!liveRoomTimerModel) return;
        NSString *key = [NSString stringWithFormat:@"%.1f", liveRoomTimerModel.startTimeValue];
        NSMutableSet *timerModesSet = [self.timerActionDic objectForKey:key];
        [timerModesSet removeObject:liveRoomTimerModel];
        [self.modelsDic removeObjectForKey:timerIdentifier];
        if (timerModesSet.count == 0) [self.timerActionDic removeObjectForKey:key];
    };
    dispatch_async(self.queue, block);
}

/** 销毁计时器 */
-(void)destoryMgr{
    if (self) {
        [self.timerActionDic removeAllObjects];
        [self.modelsDic removeAllObjects];
        dispatch_source_cancel(self.timer);
        self.timer = nil;
        self.queue = nil;
    }
}

-(void)dealloc{
    NSLog(@"==========dealloc==============");
}

@end
